package com.jin.notifyserver;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private CommandViewModel commandVM;
    private TextView tv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        commandVM = new ViewModelProvider(this).get(CommandViewModel.class);

        commandVM.getOkxDtoLiveData().observe(this, okxDto -> {
//            tv.setText(okxDto.getData().getContent());
        });

        tv = findViewById(R.id.tv_content);

        startForegroundService(new Intent(this, MQTTService.class));

        // 加入白名单
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

        if (!pm.isIgnoringBatteryOptimizations(getPackageName())) {
            try {
                @SuppressLint("BatteryLife") Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            } catch (Exception e) {
                Log.e(TAG, "onCreate: ", e);
            }
        }

        if (!AutoStartHelper.isHinted(this)) {
            // 第一次才弹提示
            new AlertDialog.Builder(this)
                    .setTitle("后台运行提示")
                    .setMessage("为了保证消息正常接收，请开启自启动/后台运行权限")
                    .setPositiveButton("去设置", (d, w) -> AutoStartHelper.goToAutoStartSetting(this))
                    .setNegativeButton("忽略", null)
                    .show();
        }

    }

    /**
     * 判断应用是否在后台运行
     */
    public static boolean isAppInBackground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        if (runningProcesses == null) return true;
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.processName.equals(context.getPackageName())) {
                return processInfo.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
            }
        }
        return true;
    }

}
